import {createRouter, createWebHistory} from 'vue-router'
import HomeView from '../views/HomeView.vue'
import {useTokenStore} from "@/stores/tokenStore";
import {ElMessage} from "element-plus";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'home',
            component: HomeView,
            children: [
                {
                    path: '/ingredients',
                    name: 'ingredients',
                    component: () => import('@/views/ingredients/index.vue')
                },
                {
                    path: '/prepare',
                    name: 'prepare',
                    component: () => import('@/views/prepare/index.vue')
                },
                {
                    path: '/order',
                    name: 'order',
                    component: () => import('@/views/order/index.vue')
                },
                {
                    path: '/dishes',
                    name: 'dishes',
                    component: () => import('@/views/dishes/index.vue')
                }
            ]
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('@/views/login/index.vue')
        }
    ]
})

router.beforeEach((to, from) => {
    const tokenStore = useTokenStore()
    const {path} = to
    if (path == '/login') {
        if (tokenStore.accessToken) { // 登录状态下访问 /login, 跳转到首页
            return {path: '/'}
        }// 没写的 else 表示 跳转到 /login
    } else {
        if (!tokenStore.accessToken) {
            ElMessage.error('请登录后操作')
            return {path: '/login', query: {destPath: path}}
        }
    }
})

export default router
